package gestoremulte.pack;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.Matrix;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/*
 * Questa Activity si occupa di prendere la targa, scattare la foto e gestire le pratiche per ACI PRA ecc
 */
public class TargaActivity  extends Activity {
	
	public static final int GET_IMAGE = 2;
	private String LocationFile = Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Foto"+File.separator;
	private static final String SERVICE_URL_VISURA_ACI_PRA = "https://91.226.109.144/GestioneMulteServer/visuraACI";

	private EditText targa;
	private Button prosegui;
	private Button scattaFoto;
	private Display display;
	private Bitmap image;
	private Button visuraACI;
	
	private String nVerbale = null;

	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.targa);
        
        targa = (EditText) findViewById(R.id.editText1);
        
        prosegui=(Button) findViewById(R.id.button2);
        prosegui.setOnClickListener(proseguiListener);
        
        scattaFoto=(Button) findViewById(R.id.button1);
        scattaFoto.setOnClickListener(cameraListener);
        display= getWindowManager().getDefaultDisplay();
        
        visuraACI=(Button) findViewById(R.id.VisuraAciPRAButton);
        visuraACI.setOnClickListener(VisuraListner);
        
        MyDatabase db=new MyDatabase(this);
        db.open();
        
        nVerbale = db.getfirstVerbale();
        
        if (nVerbale == null){
        	Toast toast =Toast.makeText(this, "Non ci sono più numeri di verbale... ricaricare i verbali",Toast.LENGTH_SHORT);
    		toast.show();
        }
        db.close();
        // Controllo sullo spazio disponibile per i salvataggi
       
	}
	
	

	
	protected void onRestart(){
    	super.onRestart();
    	if (VariabiliCondiviseApplication.restored){
    		
    		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            VariabiliCondiviseApplication.IMEI = telephonyManager.getDeviceId();
			VariabiliCondiviseApplication.online = false;
			
			CustomDialogLoginOffline dialog = new CustomDialogLoginOffline(this);
		    dialog.setCancelable(false);
		    dialog.show();
    	}
    }
	
	protected void onStart(){
    	super.onStart();
    	
    	if (VariabiliCondiviseApplication.online == false){
    		visuraACI.setEnabled(false);
    		
    		
    	}
    	
    	else{
    		visuraACI.setEnabled(true);
    		
    	}
    	
    	 if (getAvailableSpaceInMB() <=3){
    	        
         	AlertDialog.Builder builder = new AlertDialog.Builder(this);
         	builder.setMessage("Spazio disponibile per i salvataggi insufficente?")
         	       .setCancelable(false)
         	       .setPositiveButton("Continuare", new DialogInterface.OnClickListener() {
         	           public void onClick(DialogInterface dialog, int id) {
         	                dialog.dismiss();
         	           }
         	       })
         	       .setNegativeButton("Eliminare file", new DialogInterface.OnClickListener() {
         	           public void onClick(DialogInterface dialog, int id) {
         	        	   Intent i = new Intent(TargaActivity.this,CaricaNotificaVerbaleSecureActivity.class);
         	        	   startActivity(i);
         	           }
         	       });
         	AlertDialog alert = builder.create();
         	alert.show();
         }
    	 
    	
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu2, menu);
        return true;
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon: 
            	CustomDialogLoginOnline dialog = new CustomDialogLoginOnline(this);
            	dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						if (VariabiliCondiviseApplication.online == true){
							visuraACI.setEnabled(true);
				    		
				    	}
						
					}
            	});
            	dialog.show();
                break;
           
        }
        return true;
    }
	
	 private OnClickListener proseguiListener = new OnClickListener() {
	        public void onClick(View v) {
	        	
	        	Intent i = new Intent(TargaActivity.this,MultaActivity.class);
                i.putExtra("targa", targa.getText().toString());
                i.putExtra("nverbale", nVerbale);
            	startActivity(i);     	

	        	
	        }
		 };
	 
		 // attiva la camera
	 private OnClickListener cameraListener = new OnClickListener() {
	        public void onClick(View v) {
	        	Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	        	takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File (LocationFile+nVerbale+".jpg")));
	        	VariabiliCondiviseApplication.cameraAction = true;
	     	    startActivityForResult(takePictureIntent, GET_IMAGE);
	        	
	        	
	        }
		 };
		 
	// Listner per Visura ACI PRA
	 private OnClickListener VisuraListner = new OnClickListener() {
	        public void onClick(View v) {
	        	
	        	if (targa.getText().toString() == null || targa.getText().toString().length()!=7){
	        		Toast toast =Toast.makeText(v.getContext(), "Inserire correttamente la targa", Toast.LENGTH_LONG);
	        	    toast.show();
	        	}
	        	else{
		        	WebServiceSyncComunication com = new WebServiceSyncComunication(SERVICE_URL_VISURA_ACI_PRA,WebServiceSyncComunication.ACIPRA, v.getContext());
		    		com.setTarga(targa.getText().toString());
		        	com.Comunicazione();
		    		
	        	}
	        }
	 };
	//metodo richiamato quando si ritorna dall'avvio della camera	 
	 @Override 
	 protected void onActivityResult(int requestCode, int resultCode, Intent intent){ // va a leggere il contenuto dell'immagine salvata e lo comprime riscrivendola 
	    	ImageView imv = (ImageView) findViewById(R.id.imageView2);
	    	if(requestCode == GET_IMAGE && resultCode == RESULT_OK){
	    		 // Bundle extras = intent.getExtras();
	    			      


	    	     Bitmap mImageBitmap = BitmapFactory.decodeFile(LocationFile+nVerbale+".jpg"); 
	    	     
	    	     Matrix matrix = new Matrix();
	    	     matrix.postRotate(90); // la foto viene ruotata

	    	     image = Bitmap.createBitmap(mImageBitmap, 0, 0, mImageBitmap.getWidth(), mImageBitmap.getHeight(),
	    	    	        matrix, true);
	    	     
				

	    	     imv.setAdjustViewBounds(true);
	    	     imv.setMaxHeight(display.getHeight()/2);
	    	     imv.setMaxWidth(display.getWidth()-100);
	    	     
	    	     imv.setImageBitmap(image);
	    	      //ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    	      FileOutputStream out = null;
				try {
					out = new FileOutputStream(LocationFile+nVerbale+".jpg");
					image.compress(Bitmap.CompressFormat.JPEG, 60, out); // La foto viene compressa per ridurre spazio occupato e inviare meno dati
					out.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

	    		
	    		  
				VariabiliCondiviseApplication.fotoScattata = true;
	    		  VariabiliCondiviseApplication.cameraAction = false;
	    	      
	    	} 
	    	else{
	    		VariabiliCondiviseApplication.fotoScattata = false;
	    		imv.setImageResource(R.id.imageView2);
	    		File file = new File(LocationFile+nVerbale+".jpg");
	    		if (file != null)
	    			file.delete();


	    		//deleteFile(LocationFile+nVerbale+".jpg");
	    	}
	    	
	    	//else imv.setBackgroundColor(Color.RED);
	    }
	 
	
	 protected void onPause(){
	    	super.onPause();
	    	if (VariabiliCondiviseApplication.backClick || VariabiliCondiviseApplication.cameraAction)
	    		VariabiliCondiviseApplication.restored = false;
	    	else
	    		VariabiliCondiviseApplication.restored = true;
	    	VariabiliCondiviseApplication.backClick = false;
	    	
	    }
	 
	 @Override
	    public void onBackPressed() {
		 	super.onBackPressed();
	    	VariabiliCondiviseApplication.backClick = true;
	    	
	    }
	 
	 private static long getAvailableSpaceInMB(){
	    final long SIZE_KB = 1024L;
	    final long SIZE_MB = SIZE_KB * SIZE_KB;
	    long availableSpace = -1L;
	    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
	    availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
	    return availableSpace/SIZE_MB;
	}
}
